package la.iok.hzsvn.lewin.movie.interceptor;

import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Modifier;

@Component
@Intercepts(@Signature(type= Executor.class, method = "update",args = {MappedStatement.class,Object.class}))
public class TrimStringInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if(parameter == null || (sqlCommandType != SqlCommandType.INSERT && sqlCommandType != SqlCommandType.UPDATE)){
            return invocation.proceed();
        }
        if(parameter instanceof MapperMethod.ParamMap){
            MapperMethod.ParamMap<Object> param = (MapperMethod.ParamMap<Object>) parameter;
            param.forEach((k,v)->{
                if(v instanceof String){
                    param.put(k,((String) v).trim());
                }
            });
        }else{
            ReflectionUtils.doWithFields(parameter.getClass(),field->{
                field.setAccessible(true);
                String obj = (String) field.get(parameter);
                field.set(parameter,obj==null?null:obj.trim());
            },field -> String.class.equals(field.getType()) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers()));
        }
        return invocation.proceed();
    }
}
